package com.lkl.hystrixdemo.order.controller;

import com.lkl.hystrixdemo.order.aspect.annotation.LklTokenValidAnnotation;
import com.lkl.hystrixdemo.order.model.User;
import com.lkl.hystrixdemo.order.service.UserService;
import com.lkl.hystrixdemo.order.utils.MapTokenUtils;
import com.lkl.hystrixdemo.order.utils.RedisTokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * 令牌是为了，防止幂等性
 *
 * CSRF token伪造攻击
 *
 * 比如在执行核心业务的时候， 转账，投资等，虽然有令牌存在，但是令牌可以提前获取，再执行
 *
 * 可以用短信验证码解决
 *
 */
@Controller
@SuppressWarnings("all")
public class TokenController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTokenUtils redisTokenUtils;


    @RequestMapping("/getRedisToken")
    @ResponseBody
    public String getRedisToken () {
        return redisTokenUtils.getToken();
    }

    /**
     * 添加用户，防止重复提交
     * @param request
     * @return
     */
    @RequestMapping("/addRedisUser")
    @ResponseBody
    @LklTokenValidAnnotation
    public String addRedisUser (HttpServletRequest request) {
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        userService.addUser(user);
        System.out.println("addUser is starting...");
        return "success";
    }


    @RequestMapping("/getToken")
    @ResponseBody
    public String getToken () {
        return MapTokenUtils.getToken();
    }

    /**
     * 添加用户，防止重复提交
     * @param request
     * @return
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public String addUser (HttpServletRequest request) {
        String headToken = request.getParameter("token");

        if (StringUtils.isEmpty(headToken)) {
            return "令牌不存在， 非法请求";
        }

        boolean access = MapTokenUtils.isAccess(headToken);

        if (!access) {
            return "请勿重复提交";
        }

        String email = request.getParameter("email");
        String username = request.getParameter("username");

        User user = new User();
        user.setEmail(email);
        user.setUsername(username);
        userService.addUser(user);
        System.out.println("addUser is starting...");
        return "添加成功";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        String token = MapTokenUtils.getToken();
        model.addAttribute("token", token);

        model.addAttribute("token", redisTokenUtils.getToken());
        return "index";
    }

}

